package validator

import (
	"gopkg.in/go-playground/validator.v9"
	"regexp"
)

const (
	IS_VALIDUSER =  "is_validuser"
	IS_MOBILE = "is_mobile"
	IS_PASSWORD = "is_password"
)

//返回自定义方法
func createRule() rule {
	value := make(map[string]*definit)
	value[IS_VALIDUSER] = isValiduser()
	value[IS_MOBILE] = isMobile()
	value[IS_PASSWORD] = isPassword()

	return value
}

//获取字符串
func getValue(fl validator.FieldLevel) string {
	return fl.Field().String()
}

//自定义验证例子
func isValiduser() *definit {
	return newDefinit(func(fl validator.FieldLevel) bool {
		return getValue(fl) == "admin"
	}, "测试错误信息")
}

//验证手机号码
func isMobile() *definit {
	return newDefinit(func(fl validator.FieldLevel) bool {
		result, _ := regexp.MatchString(`^1(3[0-9]|5[0-3,5-9]|7[1-3,5-8]|8[0-9])\d{8}$`, getValue(fl))
		return result
	},"格式不正确")
}

//验证密码
func isPassword() *definit {
	return newDefinit(func(fl validator.FieldLevel) bool {
		result, _ := regexp.MatchString(`^[a-zA-Z0-9]{6,16}$`, getValue(fl))
		return result
	},"为6到16位的数字或字符串组成")
}

